<template>
  <el-drawer v-model="drawer" :with-header="false" direction="btt" size="500px">
    <div class="buy">
      <div class="buy__header">
        <div class="img">
          <el-image fit="fill" :src="foodItem.img_id.full_url"></el-image>
        </div>
        <div class="detail">
          <div class="px-1 py-2 truncate title">{{ foodItem.title }}</div>
          <span class="is-price">{{foodItem.skuPrice || foodItem.price || 0.00}}</span>
          <!-- <span class="ml size-12">库存：{{food.count}}件</span> -->
          <!-- <div class="selected">
            <span>库存：</span>
            <span class="ml">{{foodItem.stock || 0}} 件</span>
          </div> -->
        </div>
      </div>
      <div class="buy__container">
        <el-scrollbar>
          <div class="label mb" v-if="foodItem.sku.length">规格</div>
          <div class="sku-box" v-if="foodItem.sku.length">
            <template v-for="(item, index) in foodItem.sku[0].json.tree">
              <p class="sku-name">{{item.k}}</p>
              <el-radio-group v-model="selectSku[index]" size="small"
                @change="(data: string) => handleSkuSlect(data, item, index, food.sku[0].json.tree.length)">
                <el-space>
                  <el-radio-button v-for="sku in item.v" :label="JSON.stringify(sku)">{{sku.name}}</el-radio-button>
                </el-space>
              </el-radio-group>
            </template>
          </div>
          <div class="item">
            <div class="label">购买数量</div>
            <el-input-number v-model="foodItem.buyCount" size="mini" :min="1" :max="20"></el-input-number>
          </div>
        </el-scrollbar>
      </div>
      <div class="buy__footer">
        <el-button :disabled="!disabled" type="info" v-if="type == 0" size="small" style="width: 90%" @click="setCart">
          确定
        </el-button>
        <el-button v-else size="small" type="info" style="width: 90%" @click="buy">立即购买</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { Utoast } from "@/packages/components/toast";
import cartStore from "@/store/cartStore";
import { ElMessage } from "element-plus";
import { FoodItem } from "@/types/food";
import { ref, watch, computed, unref, onMounted, nextTick } from "vue"
import { onBeforeRouteLeave, useRouter } from "vue-router";

interface Props {
  food: FoodItem
  type: number
}

interface SKU {
  tree: Array<any>;
  list: Array<any>;
}

interface SelectSku {
  [key: string]: any;
}
const props = withDefaults(defineProps<Props>(), {})

const router = useRouter()
const cart = cartStore()

const drawer = ref(false)
const foodItem = ref<FoodItem>(props.food)
const disabled = computed(() => {
  if (foodItem.value.sku.length) {
    return foodItem.value.stock > 0 && foodItem.value.buyCount > 0
  } else {
    return true
  }

})

const selectSku = ref<string[]>([])
const selectSkuCopy = ref<SelectSku[]>([])

const sku = computed<SKU[]>(() => {
  return foodItem.value.sku as any
})
let contains = (a: any, b: any) => Object.entries(b).every(([k, v]) => {
  return a[k] === v
})
const computedOtherMsg = () => {
  let obj = {} as SelectSku
  selectSkuCopy.value.forEach(el => {
    obj = { ...obj, ...el }
  })
  console.log('obj', obj);

  let skuNameArr: string[] = []
  selectSku.value.forEach(val => {
    let item = JSON.parse(val)
    skuNameArr.push(item.name)
  })
  let skuFood = (foodItem.value as FoodItem).sku[0].json.list.find((el: any) => {
    return contains(el, obj)
  })
  if (skuFood) {
    console.log(skuFood);

    foodItem.value.skuPrice = skuFood.price
    foodItem.value.stock = skuFood.stock_num
    foodItem.value.skuId = skuFood.id
    foodItem.value.skuName = skuNameArr.join(',')
    console.log('foodItem', foodItem.value);

  }
}
watch(drawer, (value) => {
  if (!value) return
  foodItem.value = JSON.parse(JSON.stringify(props.food)) as FoodItem
  selectSku.value = []
  selectSkuCopy.value = []
  foodItem.value.buyCount = 1
  if (foodItem.value.sku.length) {
    foodItem.value.sku[0]?.json.tree.forEach(val => {
      if (val.v[0]) {
        selectSku.value.push(JSON.stringify(val.v[0]))
        selectSkuCopy.value.push({ [val.k_s]: val.v[0].id })
      }
    })
    if (selectSkuCopy.value.length === foodItem.value.sku[0]?.json?.tree.length) {
      computedOtherMsg()
      nextTick()
    }
  } else {
    // 没有sku 就把自己的价格和商品id作为这两个id
    foodItem.value.skuPrice = foodItem.value.price
    foodItem.value.skuId = foodItem.value.goods_id
  }

}, { deep: true })

onBeforeRouteLeave(() => {
  reset()
})

const reset = () => {
  selectSku.value = []
  selectSkuCopy.value = []
  foodItem.value.buyCount = 1
  drawer.value = false
}


const handleSkuSlect = (data: string, sku: any, index: number, length: number) => {
  console.log('change le');

  foodItem.value.buyCount = 1
  let value = JSON.parse(data)
  selectSkuCopy.value[index] = { [sku.k_s]: value.id }
  if (selectSkuCopy.value.length === length) {
    computedOtherMsg()
  }
}



function buy() {
  cart.setFoods([foodItem.value])
  router.push("/confirm-orders")
}
function setCart() {
  cart.addCart(foodItem.value)
  Utoast({ message: "添加购物车成功" })
  reset()
}

defineExpose({
  drawer
})

</script>

<style lang="scss" scoped>
.buy {
  padding: 10px;
  height: 100vh;
  box-sizing: border-box;
  overflow-x: hidden;

  &__header {
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    display: flex;

    .img {
      height: 80px;
      width: 80px;
    }

    .detail {
      flex: 1;
      margin-left: 10px;
      padding-top: 5px;

      .selected {
        margin-top: 5px;
        font-size: 12px;
      }
    }
  }

  &__container {
    height: 320px;

    .sku-box {
      height: 100%;

      .sku-name {
        margin-bottom: 8px;
        margin-top: 8px;

        &:first-child {
          margin-top: 0;
        }
      }
    }

    .item {
      padding: 10px 0;

      display: flex;
      justify-content: space-between;

    }
  }

  &__footer {
    height: 40px;
    margin: auto;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
}
</style>